<template>
  <view class="cart-container">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <text class="title">购物车</text>
      <text class="edit" @tap="isEdit = !isEdit">{{ isEdit ? '完成' : '编辑' }}</text>
    </view>

    <!-- 购物车列表 -->
    <scroll-view 
      scroll-y 
      class="cart-scroll"
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
      refresher-enabled
      :refresher-triggered="isRefreshing"
    >
      <!-- 空购物车 -->
      <view v-if="cartList.length === 0" class="empty-cart">
        <image src="/static/images/empty-cart.png" mode="aspectFit"></image>
        <text class="empty-tip">购物车还是空的</text>
        <text class="empty-desc">快去挑选心仪的商品吧~</text>
        <button class="go-shopping" @tap="goShopping">
          <text>去逛逛</text>
          <uni-icons type="right" size="14" color="#fff"></uni-icons>
        </button>
      </view>

      <!-- 购物车列表 -->
      <view v-else class="cart-list">
        <!-- 商家分组 -->
        <view 
          class="merchant-group"
          v-for="merchant in cartList" 
          :key="merchant.merchantId"
        >
          <!-- 商家信息 -->
          <view class="merchant-header">
            <view class="select-wrap" @tap="handleMerchantSelect(merchant)">
              <uni-icons 
                :type="merchant.selected ? 'checkbox-filled' : 'circle'"
                size="20" 
                :color="merchant.selected ? '#ff5500' : '#999'"
              ></uni-icons>
              <image class="merchant-logo" :src="merchant.logo" mode="aspectFill"></image>
              <text class="merchant-name">{{ merchant.merchantName }}</text>
            </view>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>

          <!-- 商品列表 -->
          <view class="goods-list">
            <view 
              class="goods-item"
              v-for="item in merchant.items"
              :key="item.id"
            >
              <!-- 选择框 -->
              <view class="select-wrap" @tap="handleSelect(item)">
                <uni-icons 
                  :type="item.selected ? 'checkbox-filled' : 'circle'"
                  size="20" 
                  :color="item.selected ? '#ff5500' : '#999'"
                ></uni-icons>
              </view>

              <!-- 商品信息 -->
              <image class="goods-image" :src="item.productImg" mode="aspectFill"></image>
              <view class="goods-info">
                <view class="goods-name-wrap">
                  <text class="goods-name">{{ item.productName }}</text>
                  <text class="goods-spec" v-if="item.specInfo">
                    {{ formatSpecInfo(item.specInfo) }}
                  </text>
                </view>
                <view class="goods-bottom">
                  <view class="price-wrap">
                    <text class="price-symbol">¥</text>
                    <text class="price-value">{{ item.price.toFixed(2) }}</text>
                  </view>
                  <view class="quantity-control">
                    <button 
                      class="quantity-btn minus"
                      @tap="updateQuantity(item.id, item.quantity - 1)"
                      :disabled="item.quantity <= 1"
                    >-</button>
                    <input 
                      type="number" 
                      class="quantity-input"
                      v-model="item.quantity"
                      @blur="handleQuantityBlur(item)"
                    />
                    <button 
                      class="quantity-btn plus"
                      @tap="updateQuantity(item.id, item.quantity + 1)"
                    >+</button>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部结算栏 -->
    <view class="bottom-bar" :style="{ bottom: 'calc(100rpx + env(safe-area-inset-bottom))' }">
      <view class="select-all" @tap="handleSelectAll">
        <uni-icons 
          :type="isAllSelected ? 'checkbox-filled' : 'circle'"
          size="20" 
          :color="isAllSelected ? '#ff5500' : '#999'"
        ></uni-icons>
        <text>全选</text>
      </view>
      <view v-if="!isEdit" class="total-info">
        <view class="price-wrap">
          <text>合计：</text>
          <text class="total-price">
            <text class="symbol">¥</text>
            <text class="value">{{ totalPrice.toFixed(2) }}</text>
          </text>
        </view>
        <button 
          class="checkout-btn" 
          :disabled="selectedIds.length === 0"
          @tap="goToCheckout"
        >
          结算({{ selectedCount }})
        </button>
      </view>
      <view v-else class="edit-actions">
        <button 
          class="delete-btn"
          :disabled="selectedIds.length === 0"
          @tap="handleBatchDelete"
        >
          删除({{ selectedIds.length }})
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cartList: [],
      isEdit: false,
      isRefreshing: false,
      selectedIds: [],
      totalPrice: 0,
      selectedCount: 0
    }
  },

  computed: {
    // 是否全选
    isAllSelected() {
      if (this.cartList.length === 0) return false
      return this.cartList.every(merchant => 
        merchant.items.every(item => item.selected)
      )
    }
  },

  onShow() {
    this.loadCartList()
  },

  methods: {
    // 加载购物车列表
    async loadCartList() {
      try {
        const { data } = await this.$api.cart.list()
        // 前端处理商家分组
        this.cartList = this.groupByMerchant(data)
        this.updateTotalPrice()
      } catch (error) {
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    },

    // 按商家分组
    groupByMerchant(list) {
      const groups = {}
      list.forEach(item => {
        if (!groups[item.merchantId]) {
          groups[item.merchantId] = {
            merchantId: item.merchantId,
            merchantName: item.merchantName || `商家${item.merchantId}`,
            logo: item.merchantLogo || '/static/images/default-merchant.png',
            selected: false,
            items: []
          }
        }
        
        // 安全地解析specInfo
        let parsedSpecInfo = item.specInfo
        if (typeof item.specInfo === 'string') {
          try {
            // 尝试解析JSON
            if (item.specInfo.startsWith('{')) {
              parsedSpecInfo = JSON.parse(item.specInfo)
            }
          } catch (e) {
            parsedSpecInfo = item.specInfo
          }
        }

        groups[item.merchantId].items.push({
          ...item,
          selected: false
        })
      })
      return Object.values(groups)
    },

    // 选择商品
    handleSelect(item) {
      item.selected = !item.selected
      // 更新商家选中状态
      this.cartList.forEach(merchant => {
        if (merchant.items.some(i => i.id === item.id)) {
          merchant.selected = merchant.items.every(i => i.selected)
        }
      })
      this.updateTotalPrice()
    },

    // 选择商家所有商品
    handleMerchantSelect(merchant) {
      merchant.selected = !merchant.selected
      merchant.items.forEach(item => {
        item.selected = merchant.selected
      })
      this.updateTotalPrice()
    },

    // 全选/取消全选
    handleSelectAll() {
      const selected = !this.isAllSelected
      this.cartList.forEach(merchant => {
        merchant.selected = selected
        merchant.items.forEach(item => {
          item.selected = selected
        })
      })
      this.updateTotalPrice()
    },

    // 更新商品数量
    async updateQuantity(id, quantity) {
      if (quantity < 1) return
      try {
        await this.$api.cart.updateQuantity(id, quantity)
        // 更新本地数据
        this.cartList.forEach(merchant => {
          merchant.items.forEach(item => {
            if (item.id === id) {
              item.quantity = quantity
            }
          })
        })
        this.updateTotalPrice()
      } catch (error) {
        uni.showToast({
          title: error.message || '更新失败',
          icon: 'none'
        })
      }
    },

    // 处理数量输入
    handleQuantityBlur(item) {
      const quantity = parseInt(item.quantity)
      if (isNaN(quantity) || quantity < 1) {
        item.quantity = 1
      }
      this.updateQuantity(item.id, item.quantity)
    },

    // 批量删除
    async handleBatchDelete() {
      if (this.selectedIds.length === 0) return
      
      try {
        // 使用 Promise 包装 uni.showModal
        const confirmDelete = await new Promise((resolve, reject) => {
          uni.showModal({
            title: '提示',
            content: '确定要删除选中的商品吗？',
            success: (res) => {
              resolve(res.confirm)
            },
            fail: reject
          })
        })
        
        if (!confirmDelete) return
        
        await this.$api.cart.batchRemove(this.selectedIds)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
        // 重新加载购物车列表
        await this.loadCartList()
        
      } catch (error) {
        console.error('批量删除失败:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    },

    // 更新总价和选中状态
    updateTotalPrice() {
      let total = 0
      let count = 0
      let selectedIds = []
      
      this.cartList.forEach(merchant => {
        merchant.items.forEach(item => {
          if (item.selected) {
            total += item.price * item.quantity
            count += item.quantity
            // 确保 id 是数字类型
            selectedIds.push(Number(item.id))
          }
        })
      })
      
      this.totalPrice = total
      this.selectedCount = count
      this.selectedIds = selectedIds
    },

    // 去结算
    goToCheckout() {
      if (this.selectedIds.length === 0) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none'
        })
        return
      }

      const orderPreview = {
        useCart: true,
        cartItemIds: this.selectedIds,
        totalAmount: this.totalPrice,
        merchants: this.cartList
          .filter(merchant => merchant.items.some(item => item.selected))
          .map(merchant => ({
            merchantId: merchant.merchantId,
            name: merchant.merchantName,
            logo: merchant.logo,
            totalQuantity: merchant.items.filter(item => item.selected).length,
            totalAmount: merchant.items
              .filter(item => item.selected)
              .reduce((total, item) => total + item.price * item.quantity, 0),
            items: merchant.items
              .filter(item => item.selected)
              .map(item => ({
                id: item.id,
                name: item.productName,
                image: item.productImg,
                specInfo: item.specInfo,
                price: item.price,
                quantity: item.quantity
              }))
          }))
      }
      
      uni.setStorageSync('orderPreview', orderPreview)
      
      uni.navigateTo({
        url: '/pages/order/submit/index'
      })
    },

    // 去购物
    goShopping() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    },

    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      await this.loadCartList()
      this.isRefreshing = false
    },

    // 加载更多
    loadMore() {
      // 暂不实现
    },

    // 格式化规格信息显示
    formatSpecInfo(specInfo) {
      if (!specInfo) return ''
      if (typeof specInfo === 'string') return specInfo
      if (typeof specInfo === 'object') {
        return Object.entries(specInfo)
          .map(([key, value]) => `${value}`)
          .join(' ')
      }
      return ''
    }
  }
}
</script>

<style lang="scss" scoped>
.cart-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: calc(200rpx + env(safe-area-inset-bottom)); /* 增加底部padding,为底部导航栏和结算栏留出空间 */
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .edit {
    font-size: 28rpx;
    color: #666;
    padding: 10rpx 20rpx;
  }
}

.cart-scroll {
  height: calc(100vh - 288rpx); /* 调整滚动区域高度,减去导航栏、结算栏和底部导航栏的高度 */
  margin-top: 88rpx;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;

  image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 30rpx;
  }

  .empty-tip {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 10rpx;
  }

  .empty-desc {
    font-size: 26rpx;
    color: #999;
    margin-bottom: 40rpx;
  }

  .go-shopping {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 240rpx;
    height: 80rpx;
    background: linear-gradient(to right, #ff7300, #ff5500);
    border-radius: 40rpx;
    box-shadow: 0 10rpx 20rpx rgba(255, 85, 0, 0.2);

    text {
      font-size: 28rpx;
      color: #fff;
      margin-right: 6rpx;
    }

    &:active {
      transform: scale(0.98);
    }
  }
}

.cart-list {
  .merchant-group {
    margin-bottom: 20rpx;
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;

    .merchant-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;

      .select-wrap {
        display: flex;
        align-items: center;
        flex: 1;

        .merchant-logo {
          width: 40rpx;
          height: 40rpx;
          border-radius: 8rpx;
          margin: 0 16rpx;
        }

        .merchant-name {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }
      }
    }

    .goods-list {
      .goods-item {
        display: flex;
        align-items: center;
        padding: 30rpx;
        border-bottom: 1rpx solid #f5f5f5;

        &:last-child {
          border-bottom: none;
        }

        .select-wrap {
          margin-right: 20rpx;
        }

        .goods-image {
          width: 160rpx;
          height: 160rpx;
          border-radius: 12rpx;
          background-color: #f5f5f5;
        }

        .goods-info {
          flex: 1;
          margin-left: 20rpx;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          height: 160rpx;

          .goods-name-wrap {
            .goods-name {
              font-size: 28rpx;
              color: #333;
              line-height: 1.4;
              margin-bottom: 10rpx;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              overflow: hidden;
            }

            .goods-spec {
              font-size: 24rpx;
              color: #999;
              padding: 4rpx 12rpx;
              background-color: #f8f8f8;
              border-radius: 4rpx;
              display: inline-block;
            }
          }

          .goods-bottom {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .price-wrap {
              display: flex;
              align-items: baseline;

              .price-symbol {
                font-size: 24rpx;
                color: #ff5500;
              }

              .price-value {
                font-size: 32rpx;
                color: #ff5500;
                font-weight: bold;
              }
            }

            .quantity-control {
              display: flex;
              align-items: center;
              height: 52rpx;
              border: 1rpx solid #eee;
              border-radius: 26rpx;

              .quantity-btn {
                width: 60rpx;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 24rpx;
                color: #333;
                background: none;

                &.minus {
                  border-right: 1rpx solid #eee;
                }

                &.plus {
                  border-left: 1rpx solid #eee;
                }

                &:disabled {
                  color: #ccc;
                }
              }

              .quantity-input {
                width: 80rpx;
                height: 100%;
                text-align: center;
                font-size: 28rpx;
                color: #333;
              }
            }
          }
        }
      }
    }
  }
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 99; /* 确保在底部导航栏上方 */

  .select-all {
    display: flex;
    align-items: center;

    text {
      font-size: 28rpx;
      color: #333;
      margin-left: 12rpx;
    }
  }

  .total-info {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .price-wrap {
      margin-right: 20rpx;

      text {
        font-size: 28rpx;
        color: #333;
      }

      .total-price {
        .symbol {
          font-size: 24rpx;
          color: #ff5500;
        }

        .value {
          font-size: 36rpx;
          color: #ff5500;
          font-weight: bold;
        }
      }
    }

    .checkout-btn {
      width: 200rpx;
      height: 72rpx;
      line-height: 72rpx;
      text-align: center;
      background: linear-gradient(to right, #ff7300, #ff5500);
      color: #fff;
      font-size: 28rpx;
      border-radius: 36rpx;

      &:disabled {
        background: #ddd;
      }

      &:active {
        opacity: 0.9;
      }
    }
  }

  .edit-actions {
    flex: 1;
    display: flex;
    justify-content: flex-end;

    .delete-btn {
      width: 160rpx;
      height: 72rpx;
      line-height: 72rpx;
      text-align: center;
      background-color: #ff5500;
      color: #fff;
      font-size: 28rpx;
      border-radius: 36rpx;

      &:disabled {
        background-color: #ddd;
      }

      &:active {
        opacity: 0.9;
      }
    }
  }
}
</style> 